<template>
  <el-dialog v-model="dialogVisible" title="选择用户" width="800px" @closed="handleDialogClosed">
    <div class="user-selector-container">
      <!-- 左侧部门树 -->
      <div class="department-tree">
        <el-tree
          ref="departmentTreeRef"
          :data="departmentList"
          :props="{ label: 'title', children: 'children' }"
          node-key="id"
          highlight-current
          @node-click="handleDepartmentSelect"
          empty-text="暂无部门数据"
          :loading="loadingDepartments"
        ></el-tree>
      </div>

      <!-- 右侧用户列表 -->
      <div class="user-list">
        <el-table
          :data="filteredUsers"
          height="400"
          border
          highlight-current-row
          @current-change="handleUserSelect"
          empty-text="暂无用户数据"
          v-loading="loadingUsers"
        >
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="department" label="部门" width="150" />
          <el-table-column prop="position" label="职位" />
        </el-table>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection" :disabled="!selectedUser">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { userApi } from '@/api/user'

  interface Props {
    visible: boolean
  }

  // 用户选择器中用户列表的实际数据结构
  interface UserListItem {
    id: number
    name: string
    username: string
    mobile: string
    email: string
    sex: number
    status: number
    create_time: number
    update_time: number
    dept_name: string
    position_name: string
    did: number // 部门ID
    // 添加前端需要的字段
    department?: string
    position?: string
  }

  interface Department {
    id: number
    pid: number
    title: string
    name?: string // 添加可选的name属性
    leader_ids: string
    sort: number
    remark: string
    status: number
    create_time: number
    update_time: number
    // 扩展字段
    leader?: string
    children?: Department[]
    [key: string]: any // 允许其他属性
  }

  // 缓存键名和过期时间 - 使用更具体的命名空间避免冲突
  const CACHE_KEYS = {
    DEPARTMENTS: 'oa_user_selector_departments_v2',
    USERS: 'oa_user_selector_users_v2',
  }
  const CACHE_EXPIRY = 30 * 60 * 1000 // 30分钟缓存时间

  const props = defineProps<Props>()

  const emit = defineEmits<{
    (e: 'update:visible', value: boolean): void
    (e: 'select', user: UserListItem): void
  }>()

  // 对话框可见性
  const dialogVisible = computed({
    get: () => props.visible,
    set: value => emit('update:visible', value),
  })

  // 部门树引用
  const departmentTreeRef = ref()

  // 部门列表
  const departmentList = ref<Department[]>([])

  // 用户列表
  const userList = ref<UserListItem[]>([])

  // 加载状态
  const loading = ref(false)
  const loadingDepartments = ref(false)
  const loadingUsers = ref(false)

  // 当前选中的部门ID
  const selectedDepartmentId = ref<number | null>(null)

  // 当前选中的用户
  const selectedUser = ref<UserListItem | null>(null)

  // 根据选中部门过滤的用户列表
  const filteredUsers = computed(() => {
    // 统一处理用户数据，确保字段映射正确
    const processedUsers = userList.value.map(user => ({
      ...user,
      name: user.name || user.username || '',
      department: user.dept_name || user.department || '',
      position: user.position_name || user.position || '',
    }))

    // 如果没有选中部门，显示所有用户
    if (!selectedDepartmentId.value) {
      return processedUsers
    }

    console.log('按部门过滤用户列表，部门ID:', selectedDepartmentId.value)

    // 获取选中部门及其所有下级部门的ID
    const departmentIds = getDepartmentAndChildrenIds(
      departmentList.value,
      selectedDepartmentId.value
    )
    console.log('选中部门及其下级部门ID:', departmentIds)

    // 使用用户的did字段进行精确匹配过滤
    const filtered = processedUsers.filter(user => {
      // 如果用户没有部门ID，则不显示在任何部门下
      if (!user.did || user.did <= 0) {
        return false
      }
      const userDeptId = String(user.did)
      const isInDepartment = departmentIds.includes(userDeptId)
      console.log(`用户 ${user.name} (did: ${user.did}) 是否在部门中:`, isInDepartment)
      return isInDepartment
    })

    console.log('过滤后的用户列表:', filtered)
    return filtered
  })

  // 根据部门名称查找部门 - 现在使用ID匹配，此方法可以移除
  // 保留此方法用于向后兼容，但不再使用

  // 查找指定ID的部门
  const findDepartmentById = (departments: Department[], targetId: number): Department | null => {
    for (const dept of departments) {
      if (dept.id === targetId) {
        return dept
      }
      if (dept.children && dept.children.length > 0) {
        const found = findDepartmentById(dept.children, targetId)
        if (found) {
          return found
        }
      }
    }
    return null
  }

  // 获取部门及其所有下级部门的ID
  const getDepartmentAndChildrenIds = (departments: Department[], targetId: number): string[] => {
    const ids: string[] = []

    // 查找目标部门
    const targetDept = findDepartmentById(departments, targetId)
    if (!targetDept) {
      console.log('未找到目标部门:', targetId)
      return ids
    }

    // 收集目标部门ID
    ids.push(String(targetDept.id))
    console.log('目标部门ID:', targetDept.id)

    // 递归收集所有子部门ID
    const collectChildrenIds = (dept: Department) => {
      if (dept.children && dept.children.length > 0) {
        for (const child of dept.children) {
          ids.push(String(child.id))
          console.log('子部门ID:', child.id)
          collectChildrenIds(child)
        }
      }
    }

    collectChildrenIds(targetDept)
    console.log('所有相关部门ID:', ids)
    return ids
  }

  // 处理部门选择
  const handleDepartmentSelect = (department: Department) => {
    console.log('选中部门:', department)
    selectedDepartmentId.value = department.id
    console.log('设置选中部门ID:', department.id)
  }

  // 处理用户选择
  const handleUserSelect = (user: UserListItem) => {
    console.log('选中用户:', user)
    selectedUser.value = user
  }

  // 确认选择
  const confirmSelection = () => {
    if (selectedUser.value) {
      console.log('确认选择用户:', selectedUser.value)
      // 返回完整的用户信息，包括部门和职位
      const userToReturn = {
        ...selectedUser.value,
        name: selectedUser.value.name || selectedUser.value.username || '',
        department: selectedUser.value.dept_name || selectedUser.value.department || '',
        position: selectedUser.value.position_name || selectedUser.value.position || '',
      }
      emit('select', userToReturn)
      dialogVisible.value = false
    } else {
      ElMessage.warning('请选择一个用户')
    }
  }

  // 对话框关闭时重置选择
  const handleDialogClosed = () => {
    selectedUser.value = null
    selectedDepartmentId.value = null
  }

  // 从缓存获取数据
  const getCachedData = (key: string): any => {
    try {
      const cached = localStorage.getItem(key)
      if (cached) {
        const parsed = JSON.parse(cached)
        const now = Date.now()
        if (parsed.timestamp && now - parsed.timestamp < CACHE_EXPIRY) {
          console.log(
            `从缓存获取${key}数据，有效时间剩余: ${Math.floor((CACHE_EXPIRY - (now - parsed.timestamp)) / (60 * 1000))}分钟`
          )
          return parsed.data
        } else {
          console.log(`${key}缓存已过期，将重新获取数据`)
          localStorage.removeItem(key) // 清除过期缓存
        }
      }
    } catch (error: any) {
      console.error(`获取缓存数据${key}失败:`, error)
      localStorage.removeItem(key) // 清除损坏的缓存
    }
    return null
  }

  // 设置缓存数据
  const setCachedData = (key: string, data: any) => {
    try {
      const cacheData = {
        data,
        timestamp: Date.now(),
      }
      localStorage.setItem(key, JSON.stringify(cacheData))
      console.log(`数据已保存到缓存: ${key}`)
    } catch (error: any) {
      console.error(`保存缓存数据${key}失败:`, error)
    }
  }

  // 加载部门列表
  const loadDepartments = async () => {
    loadingDepartments.value = true

    try {
      // 首先尝试从缓存获取
      const cachedDepartments = getCachedData(CACHE_KEYS.DEPARTMENTS)
      if (cachedDepartments) {
        departmentList.value = cachedDepartments
        loadingDepartments.value = false
        return
      }

      const res = await userApi.getDepartmentList()
      console.log('部门列表API响应:', res)

      if (res && res.code === 0) {
        // 直接使用返回的数据，后端已经处理好了树形结构
        const departments = Array.isArray(res.data) ? res.data : []

        // 确保每个部门都有必要的字段
        departmentList.value = departments.map(dept => ({
          ...dept,
          id: dept.id || 0,
          pid: dept.pid || 0,
          title: dept.title || (dept as any).name || '未知部门',
          children: dept.children || [],
        }))

        console.log('部门列表数据加载成功:', departmentList.value)

        // 保存到缓存
        setCachedData(CACHE_KEYS.DEPARTMENTS, departmentList.value)
      } else {
        ElMessage.error(res?.msg || '获取部门列表失败')
        departmentList.value = []
      }
    } catch (error: any) {
      console.error('获取部门列表出错:', error)
      ElMessage.error('获取部门列表失败')
      departmentList.value = []
    } finally {
      loadingDepartments.value = false
    }
  }

  // 加载用户列表
  const loadUsers = async () => {
    loadingUsers.value = true

    try {
      // 首先尝试从缓存获取
      const cachedUsers = getCachedData(CACHE_KEYS.USERS)
      if (cachedUsers) {
        userList.value = cachedUsers
        loadingUsers.value = false
        return
      }

      // 添加status=1参数，只获取状态为正常的用户
      const res = await userApi.getUserList({ page: 1, limit: 1000, status: '1' })
      console.log('用户列表API响应:', res)

      if (res && res.code === 0) {
        // 处理分页数据结构
        let users: any[] = []

        // 根据实际返回的数据结构处理
        if (res.data && typeof res.data === 'object' && Array.isArray((res.data as any).list)) {
          // 分页数据结构 {list: [...], total: 100, page: 1, limit: 10}
          users = (res.data as any).list
        } else if (Array.isArray(res.data)) {
          // 直接数组结构
          users = res.data
        } else {
          // 其他情况
          users = []
        }

        // 确保所有用户都有必要的字段
        userList.value = users.map(user => ({
          ...user,
          id: user.id || user.userid || 0,
          name: user.name || user.username || '',
          did: user.did !== undefined ? user.did : user.department_id || 0,
          department: user.dept_name || user.department || '',
          position: user.position_name || user.position || '',
        }))

        console.log('用户列表数据加载成功:', userList.value)

        // 保存到缓存
        setCachedData(CACHE_KEYS.USERS, userList.value)
      } else {
        ElMessage.error(res?.msg || '获取用户列表失败')
        userList.value = []
      }
    } catch (error: any) {
      console.error('获取用户列表出错:', error)
      ElMessage.error('获取用户列表失败')
      userList.value = []
    } finally {
      loadingUsers.value = false
    }
  }

  // 初始化数据
  onMounted(() => {
    loadDepartments()
    loadUsers()
  })

  // 打开选择器 - 暴露给父组件使用
  const open = () => {
    dialogVisible.value = true
    // 重置选择状态
    selectedUser.value = null
    selectedDepartmentId.value = null

    // 如果还没有加载数据，则加载
    if (departmentList.value.length === 0) {
      loadDepartments()
    }
    if (userList.value.length === 0) {
      loadUsers()
    }
  }

  // 暴露方法给父组件
  defineExpose({
    open,
  })
</script>

<style scoped>
  .user-selector-container {
    display: flex;
    height: 400px;
  }

  .department-tree {
    width: 250px;
    overflow: auto;
    border-right: 1px solid #dcdfe6;
    padding-right: 10px;
  }

  .user-list {
    flex: 1;
    padding-left: 10px;
    overflow: auto;
  }
</style>
